package cn.lentme.app.activity;

import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;

import java.io.IOException;

import cn.lentme.app.base.BaseActivity;
import cn.lentme.app.component.utils.HttpUtil;
import cn.lentme.app.consts.ConstPool;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PaperEditActivity extends BaseActivity {

    private EditText nameText, contentText;
    private Button sendBtn;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paper_edit);

        initView();
    }

    private void initView(){
        nameText = findViewById(R.id.paper_edit_name);
        contentText = findViewById(R.id.paper_edit_content);

        sendBtn = findViewById(R.id.paper_edit_confirm);

        sendBtn.setOnClickListener(view -> {
            sendPaper();
        });
    }

    private void sendPaper(){
        if(contentText.getText().toString().isEmpty()){
            showSnackbar(contentText, "纸条内容不能为空！");
            return;
        }
        else if(contentText.getText().toString().length() < 20){
            showSnackbar(contentText, "纸条内容字数不能少于20字！");
            return;
        }

        String name = null;
        String content = null;

        name = (nameText.getText().toString().isEmpty())
                ? "匿名"
                :nameText.getText().toString();
        content = contentText.getText().toString();

        requestSubmitPaper(name, content);
    }

    private void requestSubmitPaper(String name, String content){
        new Thread(()->{
            OkHttpClient client = HttpUtil.client;
            RequestBody body = new FormBody.Builder()
                    .add("name", name)
                    .add("content", content)
                    .build();
            Request request = new Request.Builder()
                    .url(ConstPool.PaperServerURL + "/add_letter")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .post(body)
                    .build();
            try(Response response = client.newCall(request).execute()){
                String result = null;
                if(response.code() == 200){
                    result = response.body().string();
                    contentText.setText("");
                }
                else{
                    result = "code: " + response.code() + ", " + response.message();
                }
                final String rst = result;
                handler.post(()->{
                    showSnackbar(sendBtn, rst);
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
